﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Xml.Serialization;
using System.Globalization;
using System.IO;

namespace Framework.Common.Serializer
{
    public class XmlSerializeHelper : SerializeBase<string>
    {
        #region dict

        private static Dictionary<Type, XmlSerializer> dict = new Dictionary<Type, XmlSerializer>();

        public static XmlSerializer GetSerializer(Type t)
        {
            XmlSerializer serializer;
            if (!dict.TryGetValue(t, out serializer))
            {
                serializer = new XmlSerializer(t);
                dict[t] = serializer;
            }
            return serializer;
        }
        #endregion


        public override string Serialize(object obj)
        {
            if (obj != null)
            {
                XmlSerializer serializer = GetSerializer(obj.GetType());
                using (StringWriter writer = new StringWriter())
                {
                    serializer.Serialize(writer, obj);
                    return writer.ToString();
                }
            }
            return string.Empty;
        }

        public override bool SerializeToFile(object obj, string fullPath)
        {
            if (obj != null)
            {
                XmlSerializer serializer = GetSerializer(obj.GetType());
                return base.SerializeToFile(obj, fullPath, (fs) => serializer.Serialize(fs, obj));
            }
            return false;
        }

        public override T DeSerialize<T>(string source)
        {
            if (!string.IsNullOrWhiteSpace(source))
            {
                XmlSerializer ser = GetSerializer(typeof(T));
                using (StringReader reader = new StringReader(source))
                {
                    return (T)ser.Deserialize(reader);
                }
            }
            return default(T);
        }

        public override T DeSerializeFromFile<T>(string fullPath)
        {
            XmlSerializer ser = GetSerializer(typeof(T));
            return base.DeSerializeFromFile<T>(fullPath, (fs) => ser.Deserialize(fs));
        }
    }
}
